package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022-12-10 12:08
 */
@RestController
@RequestMapping("/api/order")
@SuppressWarnings("all")
public class OrderApiController {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private CartFeignClient cartFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    // /api/order/inner/getOrderInfo/{orderId}

    /**
     * 获取订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfoById(@PathVariable("orderId") Long orderId) {
        return orderService.getOrderInfoById(orderId);
    }


    /**
     * 获取当前用户的我的订单
     * /api/order/auth/{page}/{limit}
     * @param page
     * @param limit
     * @param request
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result index(@PathVariable Long page, @PathVariable Long limit,
                        HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        Page<OrderInfo> pageParam = new Page<>(page, limit);
        IPage<OrderInfo> ipage = orderService.getPage(pageParam, userId);
        return Result.ok(ipage);
    }

    /**
     * 提交订单 -- 下单
     * /api/order/auth/submitOrder?tradeNo=NULL
     * @param orderInfo
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        // 获取到用户id
        String userId = AuthContextHolder.getUserId(request);
        // 获取前台传过来的流水号
        String tradeNo = request.getParameter("tradeNo");
        // 检验流水号
        boolean result = orderService.checkTradeCode(userId, tradeNo);
        if (!result) {
            return Result.fail().message("不能重复提交订单");
        }
        List<String> errorList = new ArrayList<>();
        // 创建异步对象集合
        List<CompletableFuture> futureList = new ArrayList<>();
        // 遍历订单明细
        for (OrderDetail orderDetail : orderInfo.getOrderDetailList()) {

            CompletableFuture<Void> checkStockCompletableFuture = CompletableFuture.runAsync(() -> {
                // 校验库存
                boolean flag = orderService.checkStock(orderDetail.getSkuId(), orderDetail.getSkuNum());
                if (!flag) {
                    errorList.add(orderDetail.getSkuId() + "库存不足");
                }
            }, threadPoolExecutor);
            futureList.add(checkStockCompletableFuture);

            CompletableFuture<Void> checkPriceCompletableFuture = CompletableFuture.runAsync(() -> {
                // 校验价格
                // 获取当前价格
                BigDecimal skuPrice = productFeignClient.getSkuPrice(orderDetail.getSkuId());
                if (orderDetail.getOrderPrice().compareTo(skuPrice) != 0) {
                    // 价格不对
                    // 获取最新的价格
                    List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.parseLong(userId));
                    // 写入缓存 -- 全部覆盖一遍
                    cartCheckedList.forEach(cartInfo -> {
                        redisTemplate.boundHashOps(RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX)
                                .put(cartInfo.getSkuId().toString(), cartInfo);
                    });
                    errorList.add(orderDetail.getSkuId() + "价格不正确");
                }
            }, threadPoolExecutor);
            futureList.add(checkPriceCompletableFuture);
        }
        // 等待执行结束，才接着往下执行
        CompletableFuture.allOf(futureList.toArray(new CompletableFuture[futureList.size()])).join();
        if(errorList.size() > 0) {
            // 说明校验失败
            return Result.fail().message(StringUtils.join(errorList, ","));
        }
        // 设置userId
        orderInfo.setUserId(Long.parseLong(userId));
        // 保存订单和订单明细
        Long orderId = orderService.submitOrder(orderInfo);
        // 删除流水号
        orderService.deleteTradeNo(userId);
        return Result.ok(orderId);
    }


    /**
     * 确认订单 -- 结算
     * /api/order/auth/trade
     * @return
     */
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request) {
        // 创建返回的结果集对象
        Map<String, Object> resultMap = new HashMap<>();
        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);
        // 用户送货地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(Long.parseLong(userId));
        // 封装用户购物清单
        List<CartInfo> cartCheckedList = cartFeignClient.getCartCheckedList(Long.parseLong(userId));
        List<OrderDetail> orderDetailList = cartCheckedList.stream().map(cartInfo -> {
            // 创建订单详情对象
            OrderDetail orderDetail = new OrderDetail();
            // 封装数据进去
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            // 更新一次实时价格
            orderDetail.setOrderPrice(productFeignClient.getSkuPrice(cartInfo.getSkuId()));
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            return orderDetail;
        }).collect(Collectors.toList());
        // 计算购物车中物品数量
        // 以sku做计算
        int skuNum = 0;
        for (OrderDetail orderDetail : orderDetailList) {
            skuNum += orderDetail.getSkuNum();
        }

        // 计算总金额
        // 使用orderInfo中的计算总金额的方法
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);
        orderInfo.sumTotalAmount(); // 计算之后就放在属性中了

        // 获取流水号
        String tradeNo = orderService.getTradeNo(userId);

        // 封装结果集
        resultMap.put("detailArrayList", orderDetailList);
        resultMap.put("userAddressList", userAddressList);
        resultMap.put("totalNum", skuNum);
        resultMap.put("totalAmount", orderInfo.getTotalAmount());
        resultMap.put("tradeNo", tradeNo);
        return Result.ok(resultMap);
    }


    /**
     * http://localhost:8204/api/order/orderSplit
     * 拆单
     * @param request
     * @return
     */
    @PostMapping("/orderSplit")
    public String orderSplit(HttpServletRequest request) {
        // 订单id
        String orderId = request.getParameter("orderId");
        // 仓库编号与商品的对照关系
        String wareSkuMap = request.getParameter("wareSkuMap");
        // 拆单 - 获取子订单集合
        List<OrderInfo> subOrderInfoList = orderService.orderSplit(orderId, wareSkuMap);
        // 创建返回结果
        List<Map> resultList = new ArrayList<>();
        subOrderInfoList.forEach(subOrderInfo -> {
            // 转化成仓储服务需要的数据
            Map<String, Object> map = orderService.initWareOrderMap(subOrderInfo);
            resultList.add(map);
        });
        return JSON.toJSONString(resultList);
    }
}
